/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.workingtimemanager.urb;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import de.workingtimemanager.urb.db.DatabaseHandler;
import de.workingtimemanager.urb.entities.Project;
import de.workingtimemanager.urb.entities.User;
import de.workingtimemanager.urb.entities.WorkDay;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.joda.time.DateTime;
import org.joda.time.Duration;
//TODO: rename timer

/**
 *
 * @author CK05102
 */
public class TimerActivity extends Activity {

    private DateTime date;
    private DateTime startTime;
    private DateTime stopTime;
    private List<DateTime> breakStartTime = new ArrayList<DateTime>();
    private List<DateTime> breakStopTime = new ArrayList<DateTime>();
    private Duration duration;
    private List<Duration> breakDuration = new ArrayList<Duration>();
    private Context context;
    private DatabaseHandler db;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.timer);
        db = new DatabaseHandler();

        createView();
    }

    private void createView() {
        // ToDo add your GUI initialization code here
        context = this;
        date = new DateTime(System.currentTimeMillis());
        dateTimeToTextView(this.getCurrentFocus(), date, R.id.timer_date_text);

        final TextView userView = (TextView) findViewById(R.id.timer_activeuser_text);
        final Button startButton = (Button) findViewById(R.id.timer_start_button);
        final Button stopButton = (Button) findViewById(R.id.timer_stop_button);
        final Button breakButton = (Button) findViewById(R.id.timer_break_button);
        breakButton.setEnabled(false);

        try {
            db.open(context);
            User activeUser = db.getActiveUser();
            Project activeProject = activeUser.getActiveProject();

            userView.setText(activeUser.getUSERNAME() + ":" + activeProject.getProjectName());
        } finally {
            db.close();
        }
        startButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                if (startButton.getText().equals(
                        getString(R.string.timer_start_button))) {
                    startTimer(v);
                    startButton.setText(R.string.timer_resume_button);
                    startButton.setEnabled(false);
                    breakButton.setEnabled(true);
                } else {
                    stopButton.setText(R.string.timer_stop_button);
                    startButton.setEnabled(false);
                    breakButton.setEnabled(true);
                }
            }
        });

        stopButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                if (stopButton.getText().equals(getString(R.string.timer_stop_button))) {
                    stopTimer(v);
                    stopButton.setText(R.string.timer_finish_button);
                    startButton.setEnabled(true);
                    breakButton.setEnabled(false);
                } else {
                    durationToTextView(v, finishTimer(v), R.id.timer_duration_text);
                    startButton.setEnabled(false);
                    stopButton.setEnabled(false);
                    breakButton.setEnabled(false);
                }
            }
        });

        breakButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                if (breakButton.getText().equals(
                        getString(R.string.timer_break_button))) {
                    breakTimer(v);
                    breakButton.setText(R.string.timer_breakfinish_button);
                    startButton.setEnabled(false);
                    stopButton.setEnabled(false);
                } else {
                    finishBreakTimer(v);
                    stopButton.setText(R.string.timer_stop_button);
                    breakButton.setText(R.string.timer_break_button);
                    stopButton.setEnabled(true);
                }
            }
        });
    }

    private void startTimer(View v) {
        this.startTime = new DateTime(System.currentTimeMillis());
    }

    private void startTimer(View v, long millis) {
        this.startTime = new DateTime(System.currentTimeMillis() + millis);
    }

    private void stopTimer(View v) {
        this.stopTime = new DateTime(System.currentTimeMillis());
    }

    private void stopTimer(View v, long millis) {
        this.stopTime = new DateTime(System.currentTimeMillis() + millis);
    }

    private void breakTimer(View v) {
        this.breakStartTime.add(new DateTime(System.currentTimeMillis()));
    }

    private void breakTimer(View v, long millis) {
        this.breakStartTime.add(new DateTime(System.currentTimeMillis()
                + millis));
    }

    private void finishBreakTimer(View v) {
        this.breakStopTime.add(new DateTime(System.currentTimeMillis()));

        Iterator<DateTime> startTimes = breakStartTime.iterator();
        Iterator<DateTime> stopTimes = breakStopTime.iterator();

        for (int i = 0; i < breakDuration.size(); i++) {
            startTimes.next();
            stopTimes.next();
        }

        while (startTimes.hasNext() && stopTimes.hasNext()) {
            breakDuration.add(new Duration(startTimes.next(), stopTimes.next()));
        }
    }

    private void finishBreakTimer(View v, long millis) {
        this.breakStopTime.add(new DateTime(System.currentTimeMillis() + millis));

        Iterator<DateTime> startTimes = breakStartTime.iterator();
        Iterator<DateTime> stopTimes = breakStopTime.iterator();

        for (int i = 0; i < breakDuration.size(); i++) {
            startTimes.next();
            stopTimes.next();
        }

        while (startTimes.hasNext() && stopTimes.hasNext()) {
            breakDuration.add(new Duration(startTimes.next(), stopTimes.next()));
        }
    }

    private Duration finishTimer(View v) {
        this.duration = new Duration(startTime, stopTime);
        long breakMillis = 0;
        Iterator<Duration> breakDurations = breakDuration.iterator();
        while (breakDurations.hasNext()) {
            breakMillis += breakDurations.next().getMillis();
        }

        try {
            db.open(this);

            User activeUser = db.getActiveUser();
            Project activeProject = activeUser.getActiveProject();
            //find activeproject and save time for it
            activeProject.addDay(new WorkDay(parseDate(date), parseTime(startTime), parseTime(stopTime), parseDuration(new Duration(this.duration.getMillis() - breakMillis))));
            db.insert(activeProject);

        } finally {
            db.close();
        }
        this.finish();

        return new Duration(this.duration.getMillis() - breakMillis);
    }

    private void dateTimeToTextView(View v, DateTime date, int viewName) {
        StringBuilder stringBuffer = new StringBuilder();
        stringBuffer.append(date.getDayOfMonth());
        stringBuffer.append("-");
        stringBuffer.append(date.getMonthOfYear());
        stringBuffer.append("-");
        stringBuffer.append(date.getYear());
        TextView targetView = (TextView) findViewById(viewName);
        targetView.setText(String.format(getString(R.string.formatestring),
                stringBuffer));
    }

    private void durationToTextView(View v, Duration duration, int viewName) {
        StringBuilder stringBuffer = new StringBuilder();
        stringBuffer.append(duration.getStandardHours()
                % getResources().getInteger(R.integer.modulo_hour));
        stringBuffer.append(":");
        stringBuffer.append(duration.getStandardMinutes()
                % getResources().getInteger(R.integer.modulo_minute));
        stringBuffer.append(":");
        stringBuffer.append(duration.getStandardSeconds()
                % getResources().getInteger(R.integer.modulo_second));
        TextView targetView = (TextView) findViewById(viewName);
        targetView.setText(String.format(getString(R.string.formatestring),
                stringBuffer));
    }

    private String parseDate(DateTime date) {
        StringBuilder stringBuffer = new StringBuilder();
        stringBuffer.append(date.getDayOfMonth());
        stringBuffer.append("-");
        stringBuffer.append(date.getMonthOfYear());
        stringBuffer.append("-");
        stringBuffer.append(date.getYear());
        //TODO: id für workdays..wegen bisher id ist name und wenn zeit weggelassen werden soll dann sind namen doppelt
        stringBuffer.append(" ");
        stringBuffer.append(date.getHourOfDay());
        stringBuffer.append(":");
        stringBuffer.append(date.getMinuteOfHour());
        return stringBuffer.toString();
    }

    private String parseTime(DateTime date) {
        StringBuilder stringBuffer = new StringBuilder();
        stringBuffer.append(date.getHourOfDay());
        stringBuffer.append(":");
        stringBuffer.append(date.getMinuteOfHour());
        stringBuffer.append(":");
        stringBuffer.append(date.getSecondOfMinute());
        return stringBuffer.toString();
    }

    private String parseDuration(Duration duration) {
        StringBuilder stringBuffer = new StringBuilder();
        stringBuffer.append(duration.getStandardHours() % getResources().getInteger(R.integer.modulo_hour));
        stringBuffer.append("h");
        stringBuffer.append(duration.getStandardMinutes() % getResources().getInteger(R.integer.modulo_minute));
        stringBuffer.append("m");
        stringBuffer.append(duration.getStandardSeconds() % getResources().getInteger(R.integer.modulo_second));
        stringBuffer.append("s");
        return stringBuffer.toString();
    }
}
